@tool
extends EditorProperty

var plugin :EditorInspectorPlugin = null

# 当前编辑的标签字典
var current_value: Dictionary = {}
# 主容器（包含折叠按钮和标签列表）
var container: VBoxContainer
# 折叠按钮
var fold_button: Button
# 标签列表容器
var tags_container: VBoxContainer
# 更新标记，避免重复触发
var updating: bool = false
# 折叠状态
var is_folded: bool = true

func _init():
	# 创建主容器
	container = VBoxContainer.new()
	
	# 创建折叠按钮（仅在初始化时创建）
	fold_button = Button.new()
	fold_button.toggle_mode = true
	fold_button.button_pressed = false  # 默认未按下（折叠）
	fold_button.pressed.connect(_on_fold_button_toggled)
	fold_button.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	fold_button.flat = true  # 模仿原生样式，无边框
	container.add_child(fold_button)
	
	# 创建标签列表容器
	tags_container = VBoxContainer.new()
	tags_container.visible = false  # 默认折叠
	container.add_child(tags_container)
	
	add_child(container)
	set_bottom_editor(container)

func _ready():
	# 初始加载 Meta 数据
	refresh_value()

func refresh_value():
	# 从节点获取 Meta 数据
	var node = get_edited_object()
	if node and node.has_meta("tag"):
		current_value = node.get_meta("tag") as Dictionary
	else:
		current_value = {}
	
	# 记录当前的折叠状态
	var was_folded = is_folded
	
	# 更新折叠按钮文本和工具提示（不重建 fold_button）
	fold_button.text = "Tags (Size: %d)" % current_value.size()
	var tooltip = "Tags: " + "\r\n".join(current_value.keys()) if not current_value.is_empty() else "No Tags"
	fold_button.tooltip_text = tooltip
	container.tooltip_text = tooltip
	
	# 清空现有标签控件（仅更新 tags_container 的子控件）
	for child in tags_container.get_children():
		child.queue_free()
	
	# 为每个标签创建 LineEdit 和删除按钮
	var index = 0
	for tag in current_value.keys():
		var hbox = HBoxContainer.new()
		hbox.add_theme_constant_override("separation", 4)  # 控件间距
		
		# 标签索引（模仿原生样式）
		var label = Label.new()
		label.text = "[%d]" % index
		label.custom_minimum_size = Vector2(40, 0)  # 固定宽度
		hbox.add_child(label)
		
		# LineEdit
		var line_edit = LineEdit.new()
		line_edit.text = tag
		line_edit.size_flags_horizontal = Control.SIZE_EXPAND_FILL  # 扩展填充剩余空间
		line_edit.text_submitted.connect(_on_line_edit_text_submitted.bind(tag))
		line_edit.focus_exited.connect(_on_line_edit_focus_exited.bind(line_edit, tag))
		hbox.add_child(line_edit)
		
		# 删除按钮
		var delete_button = Button.new()
		delete_button.text = "X"
		delete_button.custom_minimum_size = Vector2(24, 0)  # 固定宽度
		delete_button.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
		delete_button.pressed.connect(_on_delete_button_pressed.bind(tag))
		hbox.add_child(delete_button)
		
		tags_container.add_child(hbox)
		index += 1
	
	# 添加“新标签”按钮，放在下方
	var add_button = Button.new()
	add_button.text = "Add New Tag"
	add_button.custom_minimum_size = Vector2(100, 0)
	add_button.size_flags_horizontal = Control.SIZE_SHRINK_CENTER  # 居中对齐
	add_button.pressed.connect(_on_add_button_pressed)
	tags_container.add_child(add_button)
	
	# 恢复折叠状态
	is_folded = was_folded
	fold_button.button_pressed = !is_folded  # 同步按钮状态
	tags_container.visible = !is_folded
	_update_fold_button()

func _on_fold_button_toggled():
	# 切换折叠状态
	is_folded = !fold_button.button_pressed
	tags_container.visible = !is_folded
	_update_fold_button()

func _update_fold_button():
	# 更新按钮图标（模仿原生样式）
	if is_folded:
		fold_button.icon = get_theme_icon("GuiTreeArrowRight", "EditorIcons")
	else:
		fold_button.icon = get_theme_icon("GuiTreeArrowDown", "EditorIcons")
	plugin.is_folded = is_folded

func _on_line_edit_text_submitted(new_text: String, old_tag: String):
	if updating or new_text == old_tag:
		return
	
	# 防止空键或重复键
	if new_text.is_empty() or current_value.has(new_text):
		return
	
	# 更新字典：移除旧键，添加新键
	current_value.erase(old_tag)
	current_value[new_text] = true
	update_meta()
	refresh_value()

func _on_line_edit_focus_exited(line_edit: LineEdit, old_tag: String):
	if updating or line_edit.text == old_tag:
		return
	
	# 防止空键或重复键
	if line_edit.text.is_empty() or current_value.has(line_edit.text):
		return
	
	# 更新字典：移除旧键，添加新键
	current_value.erase(old_tag)
	current_value[line_edit.text] = true
	update_meta()
	refresh_value()

func _on_delete_button_pressed(tag: String):
	if updating:
		return
	
	# 删除指定标签
	current_value.erase(tag)
	update_meta()
	refresh_value()

func _on_add_button_pressed():
	if updating:
		return
	
	# 添加新标签（避免重复）
	var new_tag = "new_tag"
	var counter = 1
	while current_value.has(new_tag):
		new_tag = "new_tag_" + str(counter)
		counter += 1
	
	current_value[new_tag] = true
	update_meta()
	refresh_value()

func update_meta():
	# 更新节点的 Meta 数据
	var node = get_edited_object()
	if node:
		updating = true
		# 确保 Meta 数据更新
		node.set_meta("tag", current_value)
		# 明确指定属性路径为 "tags"
		emit_changed("tags", current_value)
		# 通知 SceneDock 插件（如果存在）
		if get_tree():
			get_tree().emit_signal("node_configuration_changed", node)
		# 强制触发 Inspector 刷新
		var editor = EditorInterface
		if editor:
			var edited_node = editor.get_edited_scene_root()
			if edited_node:
				edited_node.notify_property_list_changed()
		updating = false
	else:
		push_error("Failed to update meta: Edited object is null")

func _update_property():
	# Inspector 请求更新时刷新
	refresh_value()
